package com.parktech.sun.utils;

import java.io.*;
import java.nio.channels.FileChannel;

public class FileHelper {

    public static void saveFile(InputStream zis, File file) throws IOException {

        if (file.exists()) {
            if (!file.createNewFile()) {
                throw new IOException("File have existed, and failed to remove it : " + file.getAbsolutePath());
            }
        }

        FileOutputStream fos = null;
        boolean success = false;
        try {
            fos = new FileOutputStream(file, false);
            byte[] b = new byte[8 * 1024];
            int k;
            while ((k = zis.read(b)) != -1) {
                fos.write(b, 0, k);
            }
            fos.flush();
            success = true;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ioe) {
                }
            }
            if (!success) {
                file.delete();
            }
        }
    }

    public static void deleteDir(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDir(file);
        }
        dir.delete();
    }

    public static void deleteUnderDir(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDir(file);
        }
    }

    public static void copyFile(File srcFile, File destFile) throws IOException {
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        FileChannel fcin = fis.getChannel();
        FileChannel fcout = fos.getChannel();
        fcin.transferTo(0, fcin.size(), fcout);
        fcin.close();
        fcout.close();
        fis.close();
        fos.close();
    }

    public static void copyDirectory(File srcDir, File destDir) throws IOException {

        File[] fileList = srcDir.listFiles();

        for (File aFileList : fileList) {
            if (aFileList.isFile()) {
                File descFile = new File(destDir, aFileList.getName());
                copyFile(aFileList, descFile);
            } else {
                File subDir = new File(destDir, aFileList.getName());
                subDir.mkdir();
                copyDirectory(aFileList, aFileList);
            }
        }
    }
}